package com.snoob.springcloudalibaba.common.tenxun.util;

import com.alibaba.fastjson.JSONObject;
import com.snoob.springcloudalibaba.base.BaseResult;
import com.snoob.springcloudalibaba.util.HttpHelperUtil;

import java.text.MessageFormat;

/**
 * @描述: 微信【小程序】工具类
 * @作者: lixing
 * @日期 2020/6/26 17:42
 */
public class WxXcxUtil {
    /**
     * @描述 获取AccessToken TODO 该方法不要直接调用，推荐使用定时器定时触发并存入redis缓存
     */
    public static BaseResult<String> getAccessToken(String appid, String secret) {
        String tokenUrl = MessageFormat.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", appid, secret);
        String accessTokenResponseStr = HttpHelperUtil.sendRequestHttps(tokenUrl, "GET",null);
        // 响应参数
        // TODO 正常 {"access_token":"48_m8Q1vJBnHvsq-IVKdMAl9HIcinFHirHIhON6O8CD_u1l7QNiAr2AmsxiGmhLzukXA3GQ6P_qpCp0KCpgw2upDbq-xHaPxeG7jYNYms06BJDfBYttcjmiWx-H_KvGVWIMHmwkwHXL2fW-5TJHBEQaAIAILX","expires_in":7200}
        // TODO 失败 {"errcode":40013,"errmsg":"invalid appid rid: 6115d836-490b2cfd-68dd592a"}
        JSONObject accessTokenResponseObj = JSONObject.parseObject(accessTokenResponseStr);
        if (accessTokenResponseObj.containsKey("errcode")) {
            return new BaseResult<String>().fail(accessTokenResponseObj.getString("errmsg"));
        }
        String accessToken = accessTokenResponseObj.getString("access_token");
        return new BaseResult<String>().setData(accessToken);
    }

    /**
     * @描述 获取会话信息
     */
    public static BaseResult<JSONObject> getCode2SessionByCode(String appid, String secret, String code) {
        String tokenUrl = MessageFormat.format("https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code", appid, secret, code);
        String accessTokenResponseStr = HttpHelperUtil.sendRequestHttps(tokenUrl, "GET",null);
        // 响应参数
        // TODO {"errcode":"错误码。0成功","errmsg":"错误信息","openid":"用户唯一标识","session_key":"会话密钥","unionid":"用户在开放平台的唯一标识符，若当前小程序已绑定到微信开放平台帐号下会返回"}
        JSONObject accessTokenResponseObj = JSONObject.parseObject(accessTokenResponseStr);
        if (0 != accessTokenResponseObj.getInteger("errcode")) {
            return new BaseResult<JSONObject>().fail(accessTokenResponseObj.getString("errmsg"));
        }
        return new BaseResult<JSONObject>().setData(accessTokenResponseObj);
    }
}